package com.sztx.pay.center.worker.tbschedule;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sztx.pay.center.core.service.PayFlowHandleService;
import com.sztx.pay.center.dataaccess.domain.PayFlowDO;
import com.sztx.se.core.tbschedule.task.BaseTask;
import com.taobao.pamirs.schedule.TaskItemDefine;
@Component("payFlowHandleTask")
public class PayFlowHandleTask extends BaseTask<PayFlowDO> {

	@Autowired
	private PayFlowHandleService payFlowHandleService;
	
	/**
	 * 未处理
	 */
	public static final Integer STATUS_UNPROCESS = 0;

	/**
	 * 处理中
	 */
	public static final Integer STATUS_PROCESSING = 1;

	/**
	 * 已处理失败
	 */
	public static final Integer STATUS_PROCESSED_FAILED = 2;

	/**
	 * 已处理成功
	 */
	public static final Integer STATUS_PROCESSED_SUCCESS = 3;


	@Override
	public List<PayFlowDO> selectTasks(String taskParameter, String ownSign, int taskItemNum, List<TaskItemDefine> taskItemList, int eachFetchDataNum)
			throws Exception {
		return null;
	}

	@Override
	public Object executeTask(PayFlowDO[] object, String ownSign) throws Exception {
		if (object != null) {
//			payFlowHandleService.batchUpdateHandle(object, STATUS_UNPROCESS, STATUS_PROCESSING, 0);
			for (PayFlowDO payFlowDO : object) {
				boolean hasExeception = false;
				List<Integer> unHandlestatus = new ArrayList<Integer>();
				unHandlestatus.add(STATUS_UNPROCESS);
				unHandlestatus.add(STATUS_PROCESSED_FAILED);
				List<Integer> handlestatus = new ArrayList<Integer>();
				handlestatus.add(STATUS_PROCESSING);
				try {
					// 更新未处理的任务状态变为进行中
					payFlowHandleService.updateHandle(payFlowDO.getPayFlowNo(), unHandlestatus, STATUS_PROCESSING, 0);
					
					// 处理任务
					statisticsPayFlow(payFlowDO);
				} catch (Exception e) {
					hasExeception = true;
					log.info("", e);
					continue;
				} finally {
					// 更新处理中的任务状态变为成功或失败，并且增加处理次数
					Integer newStatus = hasExeception ? STATUS_PROCESSED_FAILED : STATUS_PROCESSED_SUCCESS;
					payFlowHandleService.updateHandle(payFlowDO.getPayFlowNo(), handlestatus, newStatus, 1);
				}
			}
		}

		return null;
	}

	private void statisticsPayFlow(PayFlowDO payFlowDO) {
		payFlowHandleService.addFinance(payFlowDO);
	}

	@Override
	public Comparator<PayFlowDO> getComparator() {
		return new Comparator<PayFlowDO>() {
			@Override
			public int compare(PayFlowDO payFlowDO1, PayFlowDO payFlowDO2) {
				return payFlowDO1.getPayFlowNo().compareTo(payFlowDO2.getPayFlowNo());
			}

			@Override
			public boolean equals(Object obj) {
				return this == obj;
			}
		};
	}

}
